package com.wc._16届国特冲刺营._12图论_Kruskal_Prim算法对比拆解.城邦;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.StringTokenizer;

/**
 * @Author congge
 * @Date 2025/6/2 14:37
 * @description
 * https://www.lanqiao.cn/courses/51805/learning/?id=4072932&compatibility=false
 */
public class Main {
    /**
     * 思路：
     * Prim算法
     */
    static FastReader sc = new FastReader();
    static PrintWriter out = new PrintWriter(System.out);
    static int N = 2021, M = 10;
    static PriorityQueue<int[]> heap = new PriorityQueue<>(Comparator.comparingInt(o -> o[2]));
    static int[] p = new int[N + 10];

    public static void main(String[] args) {
        for (int i = 1; i <= N; i++) {
            p[i] = i;
            for (int j = i + 1; j <= N; j++) {
                heap.add(new int[] {i, j, get(i, j)});
            }
        }
        int res = 0;
        while (!heap.isEmpty()) {
            int[] t = heap.poll();
            int a = t[0], b = t[1], c = t[2];
            a = find(a);
            b = find(b);
            if (a != b) {
                p[a] = b;
                res += c;
            }
        }
        out.println(res);
        out.flush();
    }

    static int find(int x) {
        if (p[x] != x) p[x] = find(p[x]);
        return p[x];
    }

    static int get (int x, int y) {
        int res = 0;
        while (x > 0 || y > 0) {
            if (x % 10 != y % 10) res += x % 10 + y % 10;
            x /= 10;
            y /= 10;
        }
        return res;
    }
}

class FastReader {
    StringTokenizer st;
    BufferedReader br;

    FastReader() {
        br = new BufferedReader(new InputStreamReader(System.in));
    }

    String next() {
        while (st == null || !st.hasMoreElements()) {
            try {
                st = new StringTokenizer(br.readLine());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return st.nextToken();
    }

    int nextInt() {
        return Integer.parseInt(next());
    }

    String nextLine() {
        String s = "";
        try {
            s = br.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return s;
    }

    long nextLong() {
        return Long.parseLong(next());
    }

    double nextDouble() {
        return Double.parseDouble(next());
    }

    // 是否由下一个
    boolean hasNext() {
        while (st == null || !st.hasMoreTokens()) {
            try {
                String line = br.readLine();
                if (line == null)
                    return false;
                st = new StringTokenizer(line);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return true;
    }
}

